package com.fast.alden.admin.security.service.impl;

import com.fast.alden.admin.security.model.UserDetailsImpl;
import com.fast.alden.admin.service.SysRoleService;
import com.fast.alden.admin.service.SysUserService;
import com.fast.alden.data.model.SysRole;
import com.fast.alden.data.model.SysUser;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.findByAccount(username);
        if (user == null) {
            throw new UsernameNotFoundException("username " + username + " is not found");
        }
        List<SysRole> roles = roleService.findAllByUserId(user.getId());

        UserDetailsImpl userDetails = new UserDetailsImpl();
        userDetails.setUser(user);
        userDetails.setRoles(roles);

        return userDetails;
    }
}
